package com.fjh.springboot_01.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;

@Slf4j
@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String senderEmail;

    /**
     * 生成 4 位随机验证码
     */
    public String generateCode() {
        SecureRandom random = new SecureRandom();
        int code = 1000 + random.nextInt(9000); // 1000 - 9999
        return String.valueOf(code);
    }

    /**
     * 发送验证码邮件
     */
    public boolean sendVerificationCode(String toEmail, String verificationCode) {
        try {
            log.info("开始发送验证码邮件到 {}", toEmail);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(senderEmail);
            message.setTo(toEmail);
            message.setSubject("在线家教平台注册验证码");
            message.setText("您的验证码是：" + verificationCode + "，有效期 5 分钟。");

            javaMailSender.send(message);
            log.info("验证码邮件发送成功");
            return true;
        } catch (Exception e) {
            log.error("发送验证码邮件失败", e);
            return false;
        }
    }
}
